
// pages/outRed/outRed.js
const app = getApp()
const CryptoJS = require('../../utils/aes-jia.js')
var timestamp = Date.parse(new Date()) / 1000;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    payment: 0,
    actId:'',
    my:'',
    receiveId:'',
    count:'',
    showgroup:false,
    name:'',
    show: false,
    amountRedEnvelope: 6.66,
    blessings: "",
    amountLabel: 6.66,
    isOver: true,
    user: {},
    walletBalance: '',
    userInfo: '',
    showPayPwdInput: false,  //是否展示密码输入层
    pwdVal: '',  //输入的密码
    payFocus: true, //文本框焦点
    prepaymentRecordId: '',
    whetherSetPayPwd: '',
    appoinbtnId: 1,
    blessingsMb: [],
    blessingsnum: 0,
    blessingsxg: false,
  },
  group(){
    var that = this
    if(that.data.showgroup){
      that.setData({
        showgroup:false,
        amountRedEnvelope:6.66,
        amountLabel:6.66,
      })
    }else{
      that.setData({
        showgroup: true,
        amountRedEnvelope:'',
        amountLabel:'0.00',
      })
    }
  },
  payment(e) {
    var id = e.currentTarget.dataset.index
    this.setData({
      payment:id
    })
  },
  numberInput(e){
    e.detail.value = e.detail.value.replace(/^[0]+[0-9]*$/gi, "");
    if (e.detail.value.indexOf(".") > 0){
      e.detail.value = ''
    } if (e.detail.value.indexOf(".") == 0) {
      e.detail.value = e.detail.value.replace(/[^$#$]/g, "");
    }
    if (e.detail.value > 200) {
      e.detail.value = 200
    }
    this.setData({
      count: e.detail.value
    })
  },
  //输入金额
  amountInput: function (e) {
    e.detail.value = e.detail.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    e.detail.value = e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');

    if (e.detail.value.indexOf(".") < 0 && e.detail.value != "") {
      e.detail.value = parseFloat(e.detail.value);
    } else if (e.detail.value.indexOf(".") == 0) {
      e.detail.value = e.detail.value.replace(/[^$#$]/g, "0.");
      e.detail.value = e.detail.value.replace(/\.{2,}/g, ".");
    }
    if (e.detail.value > 500000) {
      e.detail.value = 500000
    }
    this.setData({
      amountRedEnvelope: e.detail.value,
      amountLabel: e.detail.value
    })
    if (e.detail.value == 6.66) {
      this.setData({
        appoinbtnId: 1,
      })
    } else if (e.detail.value == 11.11) {
      this.setData({
        appoinbtnId: 2,
      })
    } else if (e.detail.value == 52.0) {
      this.setData({
        appoinbtnId: 3,
      })
    } else if (e.detail.value == 131.4) {
      this.setData({
        appoinbtnId: 4,
      })
    } else if (e.detail.value == 360) {
      this.setData({
        appoinbtnId: 5,
      })
    } else if (e.detail.value == 1001) {
      this.setData({
        appoinbtnId: 6,
      })
    } else {
      this.setData({
        appoinbtnId: 0,
      })
    }
    if (e.detail.value.length == 0) {
      this.setData({
        amountLabel: '0.00',
        appoinbtnId: 0,
      })
    }

  },
  //选定金额
  appointBtn(e) {
    var that = this
    var id = e.currentTarget.dataset.id
    var num = e.currentTarget.dataset.num
    if (id == that.data.appoinbtnId) {
      that.setData({
        appoinbtnId: 0,
        amountLabel: '0.00',
        amountRedEnvelope: '',
      })
    } else {
      that.setData({
        appoinbtnId: id,
        amountRedEnvelope: num,
        amountLabel: num,
      })
    }
  },
  //输入祝福语
  blessingInput: function (e) {
    if (e.detail.value.trim().length == 0) {
      this.setData({
        blessings: ''
      })
    } else {
      this.setData({
        blessings: e.detail.value,
        blessingsxg: true,
      })
    }
  },
  //祝福语
  istemplateData() {
    var that = this
    var dictType = ''
    if (that.data.actType==1){
      dictType="RED_BLESSINGS"
    } else if (that.data.actType == 2){
      dictType = "BIRTHDAY_BANQUET_BLESSINGS"
    } else if (that.data.actType == 3){
      dictType = "HUNDRED_BLESSINGS"
    }
    app.req({
      url: "wechat/dictionary/listBydictType",
      method: "post",
      data: {
        dictType: dictType,
      },
      success: function (res) {
        if (200 == res.code) {
          console.log("祝福语", res)
          that.setData({
            blessingsMb: res.data,
            blessings: res.data[0].dictName
          })
        }
      }
    })
  },
  blessingsbtn() {
    var that = this
    var blessingsnum = that.data.blessingsnum + 1
    if (blessingsnum == that.data.blessingsMb.length) {
      blessingsnum = 0
    }
    if (that.data.blessingsxg) {
      wx.showModal({
        content: '已编辑内容将会被替换，是否确认',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            that.setData({
              blessingsnum: blessingsnum,
              blessings: that.data.blessingsMb[blessingsnum].dictName,
              blessingsxg: false,
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else {
      that.setData({
        blessingsnum: blessingsnum,
        blessings: that.data.blessingsMb[blessingsnum].dictName
      })
    }
  },
  // 塞钱进空包
  payRedPacketsClcik: function (e) {
    var that = this;
    if (that.data.amountRedEnvelope == 0 || that.data.amountRedEnvelope.length == 0) {
      wx.showToast({
        title: "请输入红包金额",
        icon: 'none',
        duration: 2000
      })
      return;
    } 
    if (that.data.showgroup && that.data.count == '') {
      wx.showToast({
        title: "请输入红包个数",
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (that.data.showgroup ){
      if (((that.data.amountRedEnvelope*100) / that.data.count)<1){
        wx.showToast({
          title: "单个红包金额不能低于0.01",
          icon: 'none',
          duration: 2000
        })
        return;
      }
    }
    if (that.data.blessings == '') {
      that.setData({
        blessings: that.data.blessingsMb[0].dictName
      })
      return;
    }
    this.setData({
      show: true
    })
  },

  //支付
  addToActivity1(e) {
    var that = this;
    var payWay = e.currentTarget.dataset.id;
    if (payWay == 0) {
      if (that.data.walletBalance < that.data.amountRedEnvelope) {
        wx.showToast({
          title: "钱包余额不足",
          icon: 'none',
          duration: 2000
        })
        return
      } else {
        if (that.data.whetherSetPayPwd) {
          that.setData({
            showPayPwdInput: true,
            payFocus: true,
          })
        } else {
          wx.showModal({
            title: '温馨提示',
            content: '为了您的账号安全，请设置支付密码',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                wx.navigateTo({
                  url: '/pages/password/password',
                })
              }
            }
          })
        }
      }
    }
  },
  addToActivity: function (e) {
    var that = this;
    var payWay = '';
    var url ='';
    if (e == 0) {
      payWay = 0
    } else {
      payWay = e.currentTarget.dataset.id;
    }
    if (that.data.isOver) {
      that.setData({
        isOver: false
      })
      if (that.data.showgroup){
        url = 'blessmini/redPacket/sendRedGroup'
        
      }else{
        url = 'blessmini/redPacket/sendRedPrivate'
      }
      var userId = that.data.user.id
      console.log("支付方式", payWay, app.globalData.url)
      if (payWay==1){
        var sourceType = 5
      }else{
        var sourceType = ''
      }
      var data = that.data;
      app.req({
        url: url,
        method: "post",
        showLoad: true,
        data: {
          actId: that.data.actId,
          actType: that.data.actType,
          sendId: userId,
          content: that.data.blessings,
          money: that.data.amountRedEnvelope,
          receiveId: that.data.receiveId,
          payWay: payWay,
          type:1,
          sourceType: sourceType,
          prepaymentRecordId: that.data.prepaymentRecordId,
          count: that.data.count
        },
        success: function (res) {
          console.log("支付", that.data.amountRedEnvelope, payWay, res)
          if (res.code == 200 && payWay == 0) {
            console.log("弹框", payWay)
            that.setData({
              show: false,
              isOver: true
            })
            wx.navigateBack({
              delta: 1
            })
            wx.showToast({
              title: "红包发送成功",
              duration: 2000
            })
          } else if (res.code == 200 && payWay == 1) {
            var paydata = res.data;
            console.log("调取", paydata)
            wx.requestPayment({
              timeStamp: paydata.prepayDate.timeStamp,
              nonceStr: paydata.prepayDate.nonceStr,
              package: 'prepay_id=' + paydata.prepayDate.prepay_id,
              signType: 'MD5',
              paySign: paydata.prepayDate.paySign,
              success(res) {
                that.setData({
                  outTradeNo: paydata.outTradeNo,
                  show: false,
                  isOver: true
                })
                wx.navigateBack({
                  delta: 1
                })
                wx.showToast({
                  title: "红包发送成功",
                  duration: 2000
                })
              },
              fail(res) {
                that.setData({
                  isOver: true
                })
                console.log("支付已取消")
                console.log(res.errMsg)
              }
            })
          } else {
            console.log('否则', payWay)
            that.setData({
              isOver: true
            })
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000
            })
          }
        },
        fail(res) {
          that.setData({
            isOver: true
          })
        }
      });
    }
  },




  removePopContent: function (e) {
    this.setData({
      show: false
    })
  },

  //获取钱包余额
  getWalletBalance: function () {
    let that = this
    app.req({
      url: "blessmini/user/myBalance",
      method: "post",
      data: '',
      success: function (res) {
        if (200 == res.code) {
          that.setData({
            walletBalance: res.data.balance
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  //预支付
  operationRecord() {
    let that = this
    var payPwd = CryptoJS.EncryptBASE64(timestamp + '|' + that.data.pwdVal)
    var amount = CryptoJS.EncryptBASE64(timestamp + '|' + that.data.amountRedEnvelope)
    console.log('预支付参数', payPwd, amount)
    app.req({
      url: "blessmini/webPayLog/operationRecord",
      method: "post",
      data: {
        payPwd: payPwd,
        amount: amount
      },
      success: function (res) {
        if (200 == res.code) {
          that.setData({
            prepaymentRecordId: res.msg,
            pwdVal: '',
          });
          console.log('预支付', that.data.prepaymentRecordId)
          that.addToActivity(0)
        } else {
          that.setData({
            pwdVal: '',
          });
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  // 支付密码
  /**
   * 隐藏支付密码输入层
   */
  hidePayLayer: function () {

    this.setData({
      pwdVal: '',
      showPayPwdInput: false,
      payFocus: false
    })

  },
  /**
   * 获取焦点
   */
  getFocus: function () {
    this.setData({ payFocus: true });
  },
  /**
   * 输入密码监听
   */
  inputPwd: function (e) {
    this.setData({ pwdVal: e.detail.value });
    if (this.data.pwdVal.length >= 6) {
      this.setData({
        showPayPwdInput: false,
        payFocus: false
      });
      this.operationRecord()
    }
  },
  //获取是否有密码
  getIspswd() {
    var that = this
    app.req({
      url: 'blessmini/user/whetherSetPayPwd',
      data: {
      },
      method: 'POST',
      success: function (res) {
        console.log('密码', res);
        if (res.code == 200) {
          that.setData({
            whetherSetPayPwd: res.data.whetherSetPayPwd
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    var that = this
    that.setData({
      actType: options.actType,
      actId: options.actId,
      receiveId: options.receiveId,
      name: options.name,
      my:options.my
    })
    if(that.data.my=='1'){
      that.setData({
        showgroup: true,
        amountRedEnvelope:'',
        amountLabel:'0.00'
      })
    }
    app.getUserInfo(function (userInfo) {
      that.setData({
        user: userInfo
      })
      that.getWalletBalance()
    })
    that.istemplateData()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    app.getUserInfo(function (userInfo) {
      that.setData({
        userInfo: userInfo
      })
      console.log('用户信息', userInfo)
    });
    that.getIspswd()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})